/*
 * @Description: 
 * @version: 
 * @Author: 171
 * @Date: 2022-09-05 12:38:46
 * @LastEditors: 171
 * @LastEditTime: 2022-09-22 19:01:26
 */
import express, { Router, Request, Response} from "express";
import qs from "qs";
import connection  from "../db"; // 获取连接实例
import jwt from 'jsonwebtoken';
import generateKey from "../encrypt/rsa";
import getMD5 from "../encrypt/md5";
import { toLiteral } from "../tools";

/* 
  对于用户的登录和注册，使用md5存储账号密码防止sql注入
  对于每个新用户的注册，给他们生成不同的公钥和私钥
  除了token，还需要把公钥传给前端，前端每次发送请求把公钥和token发给后端解析，据此获得用户信息和私钥
*/

const userRouter: Router = express.Router(); // 声明一个路由，获取自定义api

userRouter.post("/login", (req: Request, res: Response) => { // 用于处理用户登录
 
  const { account, password }: any = qs.parse(req.body.reqData); 
  const sql = `select * from my_user where account = '${account}' and password = '${password}'`;
  connection.query(sql, (err: any, result: any) => {
    if (err || result.length === 0) { // 报错或者没有用户
      const error = err || "没有该用户";
      const errorRes = qs.stringify({ message: "error", error, code: 1 });
      res.send(errorRes);
    } 
    else { 
      const { id, privateKey, publicKey } = result[0];  // 不考虑md5可能重复的结果
      const token = jwt.sign({ id }, privateKey, { // 设置token
        expiresIn: 60 * 60 * 24 * 30, // Eg: 60, "2 days", "10h", "7d"
        algorithm: 'RS256',
      });
      const dataRes = qs.stringify({ message: 'ok', token, code: 0, publicKey, id });
      res.send(dataRes);
    }
  })
});

userRouter.post("/register", (req: Request, res: Response) => { // 用于处理用户注册
  const { account, password }: any = qs.parse(req.body.reqData); 
  const { publicKey, privateKey } = generateKey();
  const sql = `insert into my_user (account, password, publicKey, privateKey) values ('${account}', '${password}', '${toLiteral(publicKey)}', '${toLiteral(privateKey)}')`;
  connection.query(sql, (err: any, result: any) => {
    if (err) {
      const errorRes = qs.stringify({ message: "error", error: err, code: 1 });
      res.send(errorRes);
    } 
    else { 
      const dataRes = qs.stringify({ message: 'ok', code: 0 });
      res.send(dataRes);
    }
  })
});


export default userRouter;